<?php

namespace App\Http\Controllers;

use App\Models\Links;
use Illuminate\Http\Request;

class LinkController extends Controller
{
    /**
     * 推广链接列表
     */
    public function index(Request $request)
    {
        $_limit = $request->limit;
        $Link = Links::where('member_id', auth('member')->id())
            ->offset($_limit[0])
            ->limit($_limit[1])
            ->orderBy('id','desc')
            ->get();
        return response(['data'=>$Link]);
    }

    /**
     * 新增修改推广链接
     * @param string $_id 推广链接id
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response]
     */
    public function edit($_id = '', Request $request)
    {
        $_member_id = auth('member')->id();
        if($_id) {
            $Link = Links::where('id',$_id)->update($request->input());
        } else {
            $Link = Links::create([
                'member_id' => $_member_id,
                'name' => $request->name,
                'link' => $request->link
            ]);
            $_id = $Link->id;
        }
        if(!$Link) {
            $_response = response(['message'=>'操作失败'], 402);
        } else {
            $_response = response(['data'=>$_id]);
        }
        return $_response;
    }

    /**
     * 获取一个推广链接详情
     * @param $_id
     * @return mixed
     */
    public function show($_id)
    {
        $Link = Links::find($_id);
        if(!$Link) {
            $_response = response(['message'=>'请求数据不存在'], 410);
        } else {
            $_response = response(['data'=>$Link]);
        }
        return $_response;
    }

    /**
     * 删除推广链接
     * @param $_id
     * @return mixed
     */
    public function destroy($_id)
    {
        if(Links::destroy($_id)) {
            $_response = response(['data'=>'success']);
        } else {
            $_response = response(['message'=>'删除失败'], 402);
        }
        return $_response;
    }
}
